#!/usr/bin/node

const log = console.log,
      fs = require('fs'),
      http = require('http'),
      https = require('https'),
      url = require('url'),
      cheerio = require('cheerio'),
      //add = 'https://maoyan.com/films?showType=1';
      add = 'https://ke.sifou.com/free';

function getPage(){ 

  let html = fs.readFileSync('./index.html'); 
  html = html.replace('/getdata','http://localhost:8080/')
  return html;
}

let movielist = [];
https.get(add, (res) => {
  let data = '';

  res.on('data', (chunk) => { data += chunk;   });

  res.on('end', () => {

    let $ = cheerio.load(data);
    let courses = $('body').find('h5.card-title>a')
    let score = $('body').find('strong.text-danger')

    for (let i = 0; i < courses.length; i++) {
      let movies = {
        movieId: '',
        movieName: '',
        movieRange: ''
      }
      let num = $(courses[i]).attr('href').lastIndexOf('/');

      movies.movieName = $(courses[i]).text();
      movies.movieId = $(courses[i]).attr('href').substring(num+1);
      movies.movieRange = $(score[i]).text();
      movielist[i] = movies;
    }
  })
})

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  if(addr.pathname == '/'){
    res.statusCode = 200;
    res.setHeader('Content-Type','text/html');
    res.end(getPage());
    return;
  }
  if(addr.pathname == '/getlist'){
    res.statusCode = 200;
    res.setHeader('Content-Type','text/json');
    res.end(JSON.stringify(movielist));
    return;
  }
  
}).listen(8080);

log('hello world');
